package com.moon.game.command.guest.player;

import java.util.ArrayList;
import java.util.List;

import com.moon.game.clazz.PlayerItemsProto.PlayerItems.PlayerItem;
import com.moon.game.command.BaseCmd;
import com.moon.game.command.RequestSession;
import com.moon.game.constants.ErrorCode;
import com.moon.game.exception.GException;
import com.moon.game.manager.ItemMG;
import com.moon.game.manager.PlayerMG;
import com.moon.game.resource.model.Item;
import com.moon.game.service.PlayerItemService;
import com.moon.game.service.PlayerService;
import com.moon.game.vos.ErrorMsg;
import com.moon.game.vos.PlayerItemVo;
import com.moon.game.vos.PlayerVo;
import com.moon.game.vos.PlayerVo.UsedItem;

/**
 * @description 查看装备
 * @author Ranger 作者 E-mail:haozi000005@163.com
 * @version 创建时间：2012-5-24 下午1:59:24
 */
public class ViewEquipsCmd extends BaseCmd {
	
	@Override
	protected void runOnce(RequestSession req) throws GException {
		switch (req.getStatus()) {
		case STATU_INIT:
			doInit(req);
			break;
		case STATU_CHECK:
			doCheckSelf(req);
			break;
		case STATU_RETURN:
			doResponse(req);
			break;
		default:
			break;
		}
	}

	@Override
	protected void doResponse(RequestSession req) throws GException {
		String[] ps = req.getClientRequest().getPs();
		if (ps == null || ps.length < 2) {
			doResponsePsError(req);
			return;
		}
		boolean refresh = Boolean.parseBoolean(ps[0]);
		String viewId = ps[1];
		PlayerVo player = PlayerMG.instance.getPlayer(viewId);
		if (player == null) {
			req.setVO("other_id", viewId);
			doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_VIEW_OFFLINE, "你访问的玩家当前不在线！"));
			return;
		}
		List<PlayerItemVo> equips = new ArrayList<PlayerItemVo>();
		List<UsedItem> playerItems = player.getUsedItem();
		if (refresh) {
			//刷新装备列表
			if (playerItems == null) {
				playerItems = new ArrayList<UsedItem>();
			}else {
				playerItems.clear();
			}
			List<PlayerItem> items = PlayerItemService.getPlayerItems(viewId);
			if (items != null) {
				for (PlayerItem item : items) {
					if (item.getIsUse()) {
						UsedItem usedItem = new UsedItem();
						PlayerService.playerItemTransUseItem(usedItem, item);
						playerItems.add(usedItem);
					}
				}
			}
			player.setUsedItem(playerItems);
		}
		
		//查看装备
		if (playerItems != null) {
			for (UsedItem useItem : playerItems) {
				final Item item = ItemMG.instance.getItem(useItem.getItemId());
				PlayerItemVo vo = new PlayerItemVo();
				vo.setName(item.getName());
				vo.setPlayerItemId(useItem.getId());
				vo.setItemId(useItem.getItemId());
				vo.setImproveLevel(useItem.getImproveLevel());
				equips.add(vo);
			}
		}
		req.setVO("view_name", player.getName());
		req.setVO("view_id", viewId);
		req.setVO("equips", equips);
		response(req, req.getClientResponse());
	}

}
